<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use think\Db;
use think\db\Where;
use app\service\orderService;
use app\service\invoiceService;
use invoice\InvoiceApi;

use \PhpOffice\PhpSpreadsheet\IOFactory;
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
class Parkgatebill extends Common{
    public function billList(){
        //根据当前账号查询区域
        $com = (new Common())->pidTokenId();
        $whe=new Where;
        $where=array();
        $whe['community_id'] = array('in',$com['community_id']);
        //根据账号查询停车场
        $parkinglist = (new orderService())->parkingList($whe);
        $this->assign('parkinglist',$parkinglist);
        //查询停车场ID
        if(!empty($parkinglist)){
            foreach($parkinglist as $park){
                $parkingNo[] = $park['parkingNo'];
            }
            //将数组转换成字符串
            $parkingNo = implode(',',$parkingNo);
        }else{
            $parkingNo = null;
        }
        $data=request()->get();
        $gateList=array();
        if (!empty($data)){
            if(!empty($data['parkingNo'])){

                $where[]=['parkingNo','=',$data['parkingNo']];
                $gateList=Db::table("parking_gatepay")->where("parkingNo",$data['parkingNo'])->select();
            }
            if(!empty($data['invoice_type'])){
                $where[]=['invoice_type','=',$data['invoice_type']];
                //$where['invoice_type'] = $data['invoice_type'];
            }
            if(!empty($data['gateid'])){

                $where[]=['gateid','=',$data['gateid']];
            }
            if((!empty($data['start_time']))&&(empty($data['end_time']))){
                $where[]=['pay_time','>=',strtotime($data['start_time'])];
            }
            if((!empty($data['end_time']))&&(empty($data['start_time']))){
                $where[]=['pay_time','<=',strtotime($data['end_time'])];
            }
            if((!empty($data['start_time']))&&(!empty($data['end_time']))){
                $where[]=[ 'pay_time',[">=",strtotime($data['start_time'])],["<=",strtotime($data['end_time'])],'and'];
            }
        }

        $this->assign("gateList",$gateList);
        //var_dump($where);
        //$where = array_filter($where);
        $export = $where;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        $this->assign("export",$export);
        $query=array_filter($data);
        $page = request()->has('page') ? request()->get('page') : 1;
        $prolist =Db::name('parkgatebillorder')
                    ->where('parkingNo','in',$parkingNo)
                    ->where($where)->order('id desc')
                    ->paginate(20, false, [
                            'page'  =>  $page,
                            'query' =>  $query
                        ]);

        $number = Db::name('parkgatebillorder')->where('parkingNo','in',$parkingNo)->where($where)->count();
        $money["ali"]=Db::name('parkgatebillorder')->where('parkingNo','in',$parkingNo)->where($where)->where("pay_type","1")->sum("pay_money");
        $money["wx"]=Db::name('parkgatebillorder')->where('parkingNo','in',$parkingNo)->where($where)->where("pay_type","2")->sum("pay_money");
        $this->assign("money",$money);
        $this->assign('number',$number);
        
        $this->assign('list',$prolist);
        $this->assign('prolist',$prolist);
        foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }
        //var_dump($data);

        return $this->fetch("bill_list");
    }


    public function getGate(){
        $parkingNo=request()->post("parkingNo");
        $data=Db::table("parking_gatepay")->where("parkingNo",$parkingNo)->select();
        $str="<option value=''>客户端</option>";
        foreach($data as $value){
            $str=$str."<option value=".$value["id"].">".$value["gateName"]."</option>";
        }
        echo $str;
    }

    public function billExcel(){

        //获取账单数据
        $export = request()->param('export');
        $export = str_replace("|","\"",$export);

        $where = json_decode($export,true);
        $parkingNo=$this->getParkingNo();

        $billlist = Db::name('parkgatebillorder')->where('parkingNo','in',$parkingNo)->where($where)->select();
        //var_dump($orderlist);die;
        if(empty($billlist)){
            return "没有数据";
        }

        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        //设置宽度为true,不然太窄了
        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);

        //设置第一栏的标题

        $objSheet->setTitle('停车直付账单');  //设置当前sheet的标题
        //设置第一栏的标题
        $objSheet->setCellValue('A1', '停车场')
            ->setCellValue('B1', '岗亭')
            ->setCellValue('C1', '金额')
            ->setCellValue('D1', '支付方式')

            ->setCellValue('E1', '付款时间');


        $i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
        $count =Db::name('parkgatebillorder')->where('parkingNo','in',$parkingNo)->where($where)->count();  //计算有多少条数据
        for ($i = 2; $i <= $count+1; $i++) {
            $objSheet->setCellValue('A' . $i, $billlist[$i-2]["parkingName"]);
            $objSheet->setCellValue('B' . $i, $billlist[$i-2]["gateName"]);
            $objSheet->setCellValue('C' . $i, $billlist[$i-2]["pay_money"]);

            $paytype="支付宝";
            if($billlist[$i-2]["pay_type"]=="2"){
                $paytype="微信";
            }


            $objSheet->setCellValue('D' . $i,$paytype);
            $objSheet->setCellValue('E' . $i, date("Y-m-d H:i:s",$billlist[$i-2]["pay_time"]));




        }
        $this->downloadExcel($newExcel, "停车直付账单", 'Xls');
    }
    function downloadExcel($newExcel, $filename, $format)
    {
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

        $objWriter->save('php://output');

        //通过php保存在本地的时候需要用到
        //$objWriter->save($dir.'/demo.xlsx');

        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
//         If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        exit;
    }
    //开票接口
    public function invoice(){
        //查询是否有access_token
        //判断是否存在该数据
        $id=request()->get("id");    
        $billinfo = Db::table("parkgatebillorder")->where("id",$id)->find();
        if (empty($billinfo)) {
            return json(['error' => '账单不存在']);
        }
        
        $info=$billinfo;
        if($billinfo['invoice_type'] == '1'){
            return json(['error' => '不能重复开票']);
        }
        $bill_entry_amount=$info['pay_money'];
        
        
        $invoiceInfo=(new invoiceService())->parkingInvoice($billinfo["parkingNo"]);
        //var_dump($invoiceInfo);die;
        $taxrate = $invoiceInfo["taxrate"];
        
        
        $tax = $info['order_money']*$taxrate;
        $bill_entry_amount= $info['order_money'];
        $info['cost_type']="车位费";
        //$inf['cost_type']="物业费";
        $invoiceDetail = "{'goodsName':'{$info['cost_type']}','specType':'','unit':'期','num':'1','price':'{$bill_entry_amount}','withTaxFlag':'1','taxRate':'{$taxrate}','tax':'{$tax}'}";
        
        $remark = '支付宝支付';
        if($info['pay_type']=="2"){
            $remark="微信支付";
        }
        
        if($invoiceInfo["userId"]=="0"){
            return "请先配置发票信息";
        }
        
        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($invoiceInfo['fp_expires_in']);
        if($second <86400){
            //未过期
            $access_token = $invoiceInfo['fp_access_token'];
        }else{
            //过期从新获取
            $res = (new invoiceService())->getToken($invoiceInfo["service_id"]);
            if(array_key_exists("error",$res)){
                return $res["error_description"];
            }
            $access_token = $res['fp_access_token'];
        }
        
        $webinfo=Db::table("webset")->where("id","1")->find();
		$appKey = $webinfo["appKey"];
     	$appSecret = $webinfo["appSecret"];
    	$token = $access_token;// please store the token and refresh it before expired
    	$taxnum = $invoiceInfo["fp_saler_tax_num"];
        
    	$url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
    	$method = "nuonuo.electronInvoice.requestBilling"; // change to your method
		$senid = uniqid(); // generate your meaningful senid
		
		$invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = time().rand(100000,999999);
        $timestmp = time(); 
        $buyerName=$info['buyerName'];
        $buyerPhone=$info['buyerPhone'];
        if(empty($buyerPhone)){
            $buyerPhone="1";
        }
        //$buyerPhone="188561510";
        $fp_saler_tax_num=$invoiceInfo['fp_saler_tax_num'];
        
        $salerTel=$invoiceInfo['phone'];
        $salerAddress=$invoiceInfo['address'];
        $salerAccount=$invoiceInfo['fp_saler_account'];
        $emt="";
        
        //var_dump($content);
        $body = "{
        \"order\": {
            \"buyerName\": \"$buyerName\",
            \"orderNo\": \"$orderNo\",
            \"invoiceDate\": \"$invoiceDate\",
            \"clerk\": \"\",
            \"salerTaxNum\": \"$fp_saler_tax_num\",
            \"salerTel\": \"$salerTel\",
            \"salerAddress\": \"$salerAddress\",
            \"salerAccount\": \"$salerAccount\",
            \"invoiceType\": \"1\",
            \"pushMode\": \"1\",
            \"buyerPhone\": \"$buyerPhone\",
            \"remark\": \"$remark\",
            \"invoiceDetail\": [$invoiceDetail],
            \"callBackUrl\": \"\"
            }
        }";
        
        //var_dump($body);//die;
       
	
        $result = InvoiceApi::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
        //var_dump($result);
		$result = json_decode($result, true);

        if($result['code'] == 'E0000'){
            $invoiceSerialNum = $result['result']['invoiceSerialNum'];
            
            $data['id'] = $info['id'];
            $data['invoice_serial_num'] = $invoiceSerialNum;
            $data['invoice_type'] = 1;
            $billinvoiceSerialNum =Db::table("parkgatebillorder")->update($data);
            
        }else{
            return json(['error' => $result['describe']]);
        }
        return json(['success' => '开票成功']);
        $this->success("付款成功");
        
    }
    
    //发票冲红
    public function Cancellation(){
        //判断是否存在该数据
        $id = request()->param('id');
	    //var_dump($id);die;
        $billinfo = Db::table("parkgatebillorder")->where("id",$id)->find();
        
        if(empty($billinfo)){
            return '账单信息错误';
        }
        //根据发票号查询开票账单
        
        if($billinfo["invoice_type"]!="1"){
            return json(['error' => '已冲红或未开票']);            
        }
        
        $info=$billinfo;
        $invoiceInfo=(new invoiceService())->parkingInvoice($billinfo["parkingNo"]);
        //根据费用类型查询税率
        $taxrate = $invoiceInfo["taxrate"];
        //$taxrate = (new billService())->taxRate($inf['cost_type']);
        $tax = $info['pay_money']*$taxrate;
        $info['cost_type']="车位费";
        $invoiceDetail = "{'goodsName':'{$info['cost_type']}','specType':'','unit':'期','num':'-1','price':'{$info['pay_money']}','withTaxFlag':'1','taxRate':'{$taxrate}','tax':'-{$tax}'}";
        $remark = '支付宝支付';
        if($info['pay_type']=="2"){
            $remark="微信支付";
        }
        
       
        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($invoiceInfo['fp_expires_in']);
        if($second < 86400){
            //未过期
            $access_token = $invoiceInfo['fp_access_token'];
        }else{
            //过期从新获取
            $res = (new invoiceService())->getToken($invoiceInfo["service_id"]);
            if(array_key_exists("error",$res)){
                return $res["error_description"];
            }
            $access_token = $res['fp_access_token'];
        }
        $invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = time().rand(100000,999999);
        $timestmp = time();
        
        
        $webinfo=Db::table("webset")->where("id","1")->find();
		$appKey = $webinfo["appKey"];
     	$appSecret = $webinfo["appSecret"];
    	$token = $access_token;// please store the token and refresh it before expired
    	$taxnum = $invoiceInfo["fp_saler_tax_num"];
        $url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
        
        $method2 = "nuonuo.electronInvoice.CheckEInvoice"; // change to your method
		$senid2 = uniqid(); // generate your meaningful senid
		$body2 = json_encode(
			array(
				"invoiceSerialNum" => array($billinfo['invoice_serial_num'])
			)
		);
        
		$result2 = InvoiceApi::sendPostSyncRequest($url, $senid2, $appKey, $appSecret, $token, $taxnum, $method2, $body2);
        $result2 = json_decode($result2, true);
         
        if($result2['code'] != 'E0000'){
           return json(['error' => $result2['describe']]);
        }
        //var_dump($result2);die;
        $invoiceCode = $result2['result'][0]['invoiceCode'];
        $invoiceNum = $result2['result'][0]['invoiceNum'];
        
    	
    	$method = "nuonuo.electronInvoice.requestBilling"; // change to your method
		$senid = uniqid(); // generate your meaningful senid
		
		$invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = time().rand(100000,999999);
        $timestmp = time(); 
        $buyerName=$info['buyerName'];
        $buyerPhone=$info['buyerPhone'];
        if(empty($buyerPhone)){
            $buyerPhone="1";
        }
        $fp_saler_tax_num=$invoiceInfo['fp_saler_tax_num'];
        $salerAddress=$invoiceInfo['address'];
        $salerTel=$invoiceInfo['phone'];
        
        $salerAccount=$invoiceInfo['fp_saler_account'];
        $body = "{
        \"order\": {
            \"buyerName\": \"$buyerName\",
            \"orderNo\": \"$orderNo\",
            \"invoiceDate\": \"$invoiceDate\",
            \"clerk\": \"\",
            \"salerTaxNum\": \"$fp_saler_tax_num\",
            \"salerTel\": \"$salerTel\",
            \"salerAddress\": \"$salerAddress\",
            \"salerAccount\": \"$salerAccount\",
            \"invoiceType\": \"2\",
            \"invoiceCode\": \"$invoiceCode\",
            \"invoiceNum\": \"$invoiceNum\",
            \"pushMode\": \"1\",
            \"buyerPhone\": \"$buyerPhone\",
            \"invoiceDetail\": [$invoiceDetail],
            \"callBackUrl\": \"\"
            }
        }";
       
           
        
        $result = InvoiceApi::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
        // var_dump($result);
		
        $result = json_decode($result, true);
        if($result['code'] == 'E0000'){
            $invoiceSerialNum = $result['result']['invoiceSerialNum'];
            
            $data['id'] = $info['id'];
            $data['invoice_serial_num'] = $invoiceSerialNum;
            $data['invoice_type'] = 2;
            $billinvoiceSerialNum =Db::table("parkgatebillorder")->update($data);
            return json(['info' => '冲红成功']);       
            
        }else{
            return json(['error' => $result['describe']]);
        }
        
    }
    
    public function CheckEInvoice() 
	{
	    $id = request()->param('id');
	    //var_dump($id);die;
        $billinfo = Db::table("parkgatebillorder")->where("id",$id)->find();
        
       
        
        $invoiceInfo=(new invoiceService())->parkingInvoice($billinfo["parkingNo"]);
        
        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($invoiceInfo['fp_expires_in']);
        if($second < 86400){
            //未过期
            $access_token = $invoiceInfo['fp_access_token'];
        }else{
            //过期从新获取
            $res = (new invoiceService())->getToken($invoiceInfo["service_id"]);
            if(array_key_exists("error",$res)){
                return $res["error_description"];
            }
            $access_token = $res['fp_access_token'];
        }
        //var_dump($access_token);die;
        $timestmp = time();
        
        $webinfo=Db::table("webset")->where("id","1")->find();
        
		$appKey = $webinfo["appKey"];
     	$appSecret = $webinfo["appSecret"];
     
    	$token = $access_token;// please store the token and refresh it before expired
    	$taxnum = $invoiceInfo["fp_saler_tax_num"];
    
    	$url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
    	$method = "nuonuo.electronInvoice.CheckEInvoice"; // change to your method
		$senid = uniqid(); // generate your meaningful senid
		$body = json_encode(
			array(
				"invoiceSerialNum" => array($billinfo['invoice_serial_num'])
			)
		);
        
		$result = InvoiceApi::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
	
	
		$result = json_decode($result, true);
		//	echo "<pre>";
        //var_dump($result);die;
        if($result['code'] == 'E0000'){
            return $this->redirect($result['result'][0]['invoiceFileUrl']);
        }else{
            return json(['error' => $result['describe']]);
        }
		return $res;
	}
    
    
}